﻿using Microsoft.EntityFrameworkCore;
using WidgetsDesign.API.DataBase;
using WidgetsDesign.API.Models;

namespace WidgetsDesign.API.Services
{
    public class UserRepository : IUserRepository
    {
        private readonly AppDbContext _context;
        public UserRepository(AppDbContext context)
        {
            _context = context;
        }
        public string GetRandomVerificationCode(int length = 4)
        {
            Random random = new Random();
            int codeLength = length;
            int minValue = (int)Math.Pow(10, codeLength - 1);
            int maxValue = (int)Math.Pow(10, codeLength) - 1;
            return random.Next(minValue, maxValue + 1).ToString();
        }
        public async Task  CreateVerificationCode(VerificationCodeModel verificationCode)
        {
            await _context.VerificationCode.AddAsync(verificationCode);
        }

        public void CreateUserInfo(UserInfo userInfo)
        {
            if (userInfo == null)
            {
                throw new ArgumentNullException(nameof(userInfo));
            }
            _context.UserInfo.Add(userInfo);
        }
        public async Task<UserInfo?> GetUserInfoByPhoneNumber(string phoneNumber)
        {
            var query = from u in _context.UserInfo
                        where u.PhoneNumber == phoneNumber
                        select u;
            var info = await query.FirstOrDefaultAsync();
            return info;
        }
        public async Task<UserInfo?> GetUserInfoByEmail(string email)
        {
            var query = from u in _context.UserInfo
                        where u.UserEmail == email
                        select u;
            var info = await query.FirstOrDefaultAsync();
            return info;
        }
        public async Task<UserInfo?> GetUserInfoById(int id)
        {
            var query = from u in _context.UserInfo
                        where u.Id == id
                        select u;
            var info = await query.FirstOrDefaultAsync();
            return info;
        }
        public async Task<UserInfo?> GetUserInfoByUuid(Guid id)
        {
            var query = from u in _context.UserInfo
                        where u.Uuid == id
                        select u;
            var info = await query.FirstOrDefaultAsync();
            return info;
        }
        public async Task ResetPassword(string email, string password)
        {
            var query = from u in _context.UserInfo
                        where u.UserEmail == email
                        select u;
            var info = await query.FirstOrDefaultAsync();
            if (info != null)
            {
                info.PassWord = password;
            }
        }
        //public async Task<int> QueryTodayVerificationCodeCount(string phoneNumber, string type)
        //{
        //    //  return await _context.VerificationCode.CountAsync(data => data.PhoneNumber == phoneNumber && data.Type == "register" && data.CreateTime==DateTime.Today);

        //    var start = DateTime.Now.Date;
        //    var end = start.AddDays(1).AddSeconds(-1);

        //    var query = from n in _context.VerificationCode
        //                where n.PhoneNumber == phoneNumber &&
        //                n.Type == type &&
        //                n.CreateTime >= start && n.CreateTime <= end
        //                select n;

        //    return await query.CountAsync();
        //}
        /// <summary>
        /// 验证 验证码 是否有效
        /// </summary>
        /// <param name="email">手机号</param>
        /// <param name="code">验证码</param>
        /// <returns>0 成功 1 未找到 2超时</returns>
        public async Task<int> ValidateVerificationCode(string email, int code)
        {
            var start = DateTime.Now.Date;
            var end = start.AddDays(1).AddSeconds(-1);
            var query = from n in _context.VerificationCode
                        where n.UserEmail == email &&
                        n.VerificationCode == code
                        select n;

            query = query.OrderByDescending(c => c.CreateTime);

            var item = await query.FirstOrDefaultAsync();

            if (item != null)
            {
                if ((DateTime.Now - item.CreateTime).TotalMinutes < 10)
                {
                    return 0;
                }
                return 2;
            }
            return 1;
        }
        public async Task<bool> SaveAsync()
        {
            return (await _context.SaveChangesAsync() >= 0);
        }
        public void UpdateWallet(int id, double value)
        {
            var query = from u in _context.UserInfo
                        where u.Id == id
                        select u;
            var info = query.FirstOrDefault();
            if (info != null)
            {
                info.Wallet += value;
            }
        }
        public async Task UploadAvatar(Guid UserId, string avatarUrl)
        {
            var query = from u in _context.UserInfo
                        where u.Uuid == UserId
                        select u;
            var info = await query.FirstOrDefaultAsync();
            if (info != null)
            {
                info.UserAvatar = avatarUrl;
            }
        }

        public async Task UpdateUserName(Guid uuid, string name)
        {
            var query = from u in _context.UserInfo
                        where u.Uuid == uuid
                        select u;
            var info = await query.FirstOrDefaultAsync();
            if (info != null)
            {
                info.UserName = name;
            }
        }

    }
}
